import { Config } from ".";

/** 显示获取host窗口，默认false */
export function getHost(config: Config) {
    const mainWV = plus.webview.getLaunchWebview();
    mainWV.evalJS(`setLog("获取最优路线……");`);
    const wv = plus.webview.create(config.targetUrl + "/get-started", "hostWV");

    console.log("getApi-run");

    wv.show("slide-in-right" as PlusWebviewAnimationTypeShow);
    wv.addEventListener("loaded" as PlusWebviewWebviewEvent, (e) => {
        // 延时2秒，防止页面执行脚本出错
        setTimeout(() => {
            let url = wv.getURL();
            console.log("loaded", url);
            if (url.includes("/login")) {
                console.log("登录……");
                //登录页
                wv.evalJS(`window.config = ${JSON.stringify(config)}`);
                wv.evalJS(`(${pageRunFn.login.toString()})()`);
            } else if (url.includes("/get-started")) {
                console.log("登录成功");
                // 首页
                wv.loadURL(config.targetUrl + "/status");
            } else if (url.includes("/status")) {
                //链接页
                wv.evalJS(`window.config = ${JSON.stringify(config)}`);
                wv.evalJS(`(${pageRunFn.getApiUrl.toString()})()`);
            } else {
                console.log("没有处理页面", url);
                mainWV.evalJS(`setLog("未知的路径 ${url.split("com")[1]}");`);
                plus.webview.getWebviewById("scriptWV").evalJS(`__AppFlag__.setConfig()`);
                wv.close("slide-out-right" as PlusWebviewAnimationTypeClose);
            }
        }, 2 * 1000);
    });
}

const pageRunFn = {
    login: function () {
        console.log("config.userName", window.config.userName);

        let loginTime = localStorage.getItem("loginTime");

        if (loginTime && Date.now() - +loginTime < 10 * 60 * 1000) {
            //前10秒内登录过，判断为登录失败
            console.log("登录失败", window.config);

            let topWV = plus.webview.getLaunchWebview(),
                scriptWV = plus.webview.getWebviewById("scriptWV"),
                wv = plus.webview.getWebviewById("hostWV");
            localStorage.removeItem("loginTime");
            topWV.evalJS(`setLog('登录失败')`);
            setTimeout(() => {
                scriptWV.evalJS(`__AppFlag__.setConfig()`);
                wv.close("slide-out-right" as PlusWebviewAnimationTypeClose);
            }, 3 * 1000);
            return;
        }
        document.querySelector<HTMLInputElement>(".input-block-level")!.value = window.config.userName;
        document.querySelector<HTMLInputElement>("#password")!.value = window.config.password;
        setTimeout(() => {
            localStorage.setItem("loginTime", Date.now().toString());
            console.log("set-loginTime", location.href, localStorage.getItem("loginTime"));
            document.querySelector<HTMLElement>("#loginBtn")!.click();
        }, 1000);

        //5秒钟后刷新页面，防止账号密码错误一直停留在登录页面
        setTimeout(() => {
            location.reload();
        }, 5 * 1000);
    },
    getApiUrl: function () {
        let domList = document.querySelectorAll(".table tbody tr"),
            topWV = plus.webview.getLaunchWebview(),
            scriptWV = plus.webview.getWebviewById("scriptWV"),
            url = "";
        domList.forEach((v) => {
            let text = v.querySelector("th")!.innerText;
            if (v.querySelector("td")!.innerText == window.config.projectName && text.includes("https")) {
                url = text;
            }
        });
        if (url) {
            console.log("最新地址：", url);
            window.config.host = url;
            scriptWV.evalJS(`__AppFlag__.updateConfig(${JSON.stringify(window.config)});`);
            scriptWV.evalJS(`__AppFlag__.run()`);
        } else {
            topWV.evalJS(`setLog('没有可用的路线，请稍后再试。');`);
            scriptWV.evalJS(`__AppFlag__.setConfig(2000)`);
        }

        plus.webview.getWebviewById("hostWV").close("slide-out-right" as PlusWebviewAnimationTypeClose);
    },
};
